﻿using System;
using System.Collections.Generic;
using Assist;
using Autodesk.Revit.DB;
using YArchitech.Revit;

namespace YJKArch.DimensionModule
{
	internal class EditDimensionCommon
	{
		private static List<Curve> GetAxisCurves(Autodesk.Revit.DB.Document doc, Element axis)
		{
			List<Curve> list = new List<Curve>();
			if (axis.GetType() == typeof(Grid))
			{
				list.AddRange(EditDimensionCommon.GetGridCurves(doc, axis));
			}
			else if (axis.GetType() == typeof(MultiSegmentGrid))
			{
				foreach (ElementId elementId in (axis as MultiSegmentGrid).GetGridIds())
				{
					Element elementById = doc.GetElementById(elementId);
					list.AddRange(EditDimensionCommon.GetGridCurves(doc, elementById));
				}
			}
			return list;
		}

		private static List<Curve> GetGridCurves(Autodesk.Revit.DB.Document doc, Element grid)
		{
			List<Curve> list = new List<Curve>();
			Options options = doc.Application.Create.NewGeometryOptions();
			options.ComputeReferences = true;
			options.IncludeNonVisibleObjects = false;
			options.View = doc.ActiveView;
			foreach (GeometryObject geometryObject in RevitVersionFuncs.GetGeometryObjectArray(grid.get_Geometry(options)))
			{
				if (geometryObject is Line)
				{
					Line item = geometryObject as Line;
					list.Add(item);
				}
				else if (geometryObject is Arc)
				{
					Arc item2 = geometryObject as Arc;
					list.Add(item2);
				}
			}
			return list;
		}

		public static ReferenceArray HandleAxis(Autodesk.Revit.DB.Document doc, ReferenceArray array)
		{
			ReferenceArray referenceArray = new ReferenceArray();
			foreach (object obj in array)
			{
				Reference reference = (Reference)obj;
				Grid grid =  doc.GetElement(reference.ElementId) as Grid;
				if (grid != null)
				{
					GridType elem = doc.GetElement(grid.GetTypeId()) as GridType;
					int num = elem.GetParameter(BuiltInParameter.GRID_CENTER_SEGMENT_STYLE).AsInteger();
					if (num != 0)
					{
						elem.GetParameter(BuiltInParameter.GRID_CENTER_SEGMENT_STYLE).Set(0);
						doc.Regenerate();
					}
					List<Curve> axisCurves = EditDimensionCommon.GetAxisCurves(doc, grid);
					for (int i = 0; i < axisCurves.Count; i++)
					{
						if (axisCurves[i].Reference == null)
						{
							axisCurves.RemoveAt(i);
							i--;
						}
					}
					if (axisCurves.Count == 1)
					{
						Line line = axisCurves[0] as Line;
						referenceArray.Append(line.Reference);
						if (num != 0)
						{
							elem.GetParameter(BuiltInParameter.GRID_CENTER_SEGMENT_STYLE).Set(num);
						}
					}
					else if (num != 0)
					{
						elem.GetParameter(BuiltInParameter.GRID_CENTER_SEGMENT_STYLE).Set(num);
					}
				}
				else
				{
					referenceArray.Append(reference);
				}
			}
			return referenceArray;
		}
	}
}
